package com.study.custom.mybatis;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/12/23 21:17
 */
public class DefaultSqlSession implements SqlSession {
    public <T> T getMapper(Class<T> clazz) {
       return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new MapperProxyFactory(this));
    }

    public void close() {

    }

    public <E> List<E> selectList(String statement) {
        //获取对应的Mapper
        Mapper mapper = cfg.getMappers().get(statement);
        //JDBC操作流程实现
        if(mapper != null){
            return Executor.list(cfg.getConnection(), mapper);
        }
        return null;
    }

    public <E> E selectOne(String statement, Object[] args) {
        //获取对应的Mapper
        Mapper mapper = cfg.getMappers().get(statement);
        //JDBC操作流程实现
        if(mapper!=null) {
            //执行查询
            Connection conn = null;
            PreparedStatement stm = null;
            ResultSet resultSet = null;
            try {
                //获取Connection对象
                conn = cfg.getConnection();
                String sql = mapper.getSql();
                //获取PreparedStatment
                stm = conn.prepareStatement(mapper.getSql());
                stm.setInt(1, ((Long) args[0]).intValue());
                if (args.length > 1) {
                    stm.setString(2, (String) args[1]);
                }
                //执行查询
                resultSet = stm.executeQuery();
                //调用Converter实现转换
                E e = Converter.conver(resultSet, Class.forName(mapper.getResultType()));
                return e;
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if(resultSet!=null){
                        resultSet.close();
                    }
                    if(stm!=null){
                        stm.close();
                    }
                    //关闭Connection
                    this.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //把Configuration对象给DefaultSqlSession
    private Configuration cfg;
    //创建一个set方法，给Configuration赋值
    public void setCfg(Configuration cfg) {
        this.cfg = cfg;
    }

}
